package org.real.guetshop.utils;


import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.real.guetshop.constant.MessageConstant;
import org.real.guetshop.exception.ValifyCodeException;
import org.real.guetshop.pojo.dto.ValifyDTO;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class EmailUtil {

    @jakarta.annotation.Resource
    private JavaMailSender javaMailSender;

    @jakarta.annotation.Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @param title 内容
     * @return
     */
    public String buildContent(String title){
        //加载邮件的html模板
        Resource resource = new ClassPathResource("mailtemplate.ftl");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.info("发送邮件读取模板失败：{}",e.getMessage());
        }finally {
            if(fileReader != null){
                try{
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(),title);
    }

    /**
     * 向用户邮箱发送短信
     *
     * @param email 收件人邮箱
     */
    public Integer sendEmail(String email){
        //调用 javaMailSender.createMimeMessage() 方法获发送所需的参数MimeMessage
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //获取验证码，存入redis
            Integer randomCode = (int) ((Math.random() * 9 + 1) * 100000);
            //将验证码临时存到redis中
            String valifyKey = "valifyCode_" + email;
            redisTemplate.opsForValue().set(valifyKey,randomCode,30, TimeUnit.MINUTES);

            //邮箱发送内容组成
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setText(buildContent(randomCode + ""),true);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setFrom("桂电商业街" + '<' + "m17878660695@163.com" + '>');
            javaMailSender.send(mimeMessage);

            return randomCode;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }


    @SneakyThrows
    public void valify(ValifyDTO valifyDTO){
        //先校验验证码
        String valifyKey = "valifyCode_" + valifyDTO.getEmail();
        Integer valifyCode = (Integer) redisTemplate.opsForValue().get(valifyKey);
        if (valifyCode == null || !Objects.equals(valifyDTO.getValifyCode(), valifyCode)) {
            throw new ValifyCodeException(MessageConstant.VALIFYCODE_ERROR);
        }
    }
}
